<?php

namespace App\Services\Pay\Order;

use App\Core\Traits\Numeral;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Game\Pay\Order\Wallet as Order;
use App\Exports\Pay\WalletExport;

class WalletService extends Service
{
    use DatabaseMysql, Numeral;

    /**
     * 导出数据
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return false|void
     */
    private function export($query, $request, bool $export)
    {
        if (!$export) {
            return false;
        }
        // 前端排序
        $this->makeOrderParam($request, $query);
        // 平台信息
        $query->with('org:code,name');
        // 导出文件
        WalletExport::query($query)->download();
    }

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]
     */
    public function getList($request, $export = false)
    {
        $query = Order::query();

        // 筛选【平台】
        $this->makeWhereParamOrg($request, $query);
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query);
        // 筛选【搜索】
        $this->makeWhereParamSearch($request, $query);
        // 筛选【类型】
        $this->makeWhereParam($request, 'payment', $query);
        // 筛选【状态】
        $this->makeWhereParam($request, 'status', $query);

        // 导出数据
        $this->export($query, $request, $export);

        // 数据条数
        $total = (clone $query)->count();
        // 统计数据
        $stats = $this->getStats(clone $query);
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->with('org:code,name')->get([
            'id', 'sn', 'uid', 'plat_code', 'account_id', 'payment',
            'consume', 'take_back', 'usd', 'status', 'created', 'updated',
        ]);

        return [
            $collection,
            $total,
            $stats
        ];
    }

    /**
     * 获取统计信息
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return array
     */
    private function getStats($query)
    {
        // USD【合计】
        $usd = (clone $query)->getQuery()->selectRaw(implode(',', [
            "IFNULL(CAST(SUM(usd->'$.consume_sum') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS consume",
            "IFNULL(CAST(SUM(usd->'$.take_back_sum') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS take_back",
        ]))->first();

        return [
            'usd' => $usd,
        ];
    }
}
